package com.aierjun.test;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.aierjun.test.APIManager.API;
import com.aierjun.test.utils.ClearCacheUtils;
import com.aierjun.test.utils.LogUtils;
import com.aierjun.test.utils.SettingsWebViewUtils;
import com.aierjun.test.utils.SharedPreferencesUtils;

import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaChromeClient;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewClient;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends CordovaActivity {
    private CordovaWebView webView;
    private ImageView imageView;
    private FrameLayout root;
    private boolean first=true;
    private ProgressDialog pd;
    private boolean goback=false;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==233){
                String url=(String) msg.obj;
                if (url.equals("")){
                    onBackPressed();
                    LogUtils.LogUtils("onBackPressed"+"   handler   .........         ");
                }else{
                    webView.loadUrl("http://"+url);
                    LogUtils.LogUtils("http://"+"   handler  else .........         ");
                }
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one_webview);
        SharedPreferencesUtils.save(MainActivity.this,999,"goin");
        findView();
        initView();
        progressDialog();
    }

    private void progressDialog(){
        pd = new ProgressDialog(MainActivity.this);//加载的ProgressDialog
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);//选择加载风格 这里是圆圈 STYLE_HORIZONTAL 是水平进度条
        pd.setMessage("");
    }

    private void findView() {
        webView= (CordovaWebView) findViewById(R.id.one_webview_view);
        imageView= (ImageView) findViewById(R.id.one_webview_imageview);
        root= (FrameLayout) findViewById(R.id.root);
    }

    private void initView() {
        WebSettings webSettings=webView.getSettings();
        SettingsWebViewUtils.setSettings(MainActivity.this,webSettings);
        webView.addJavascriptInterface(new WebHost(this), "js");
        loadUrl("http://www.woxiangwoxiang.com:8013");
    }

    @Override
    public void init() {
        this.init(webView, new CordovaWebViewClient(this, webView) {
            // 页面加载完成事件
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                SharedPreferencesUtils.save(MainActivity.this,999,"goin");
                return super.shouldOverrideUrlLoading(view,url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        }, new CordovaChromeClient(this, webView) {
            // 页面加载中的事件
            @Override
            public void onProgressChanged(final WebView view, int newProgress) {
                int eight=SharedPreferencesUtils.getToken(MainActivity.this,"back");
                int nine=SharedPreferencesUtils.getToken(MainActivity.this,"goin");
                pd.show();
                if (eight==888){   // 返回执行的代码
                    if (newProgress==100) {
                        pd.dismiss();
                        if(imageView!=null){
                            imageView.setVisibility(View.GONE);
                            webView.setVisibility(View.INVISIBLE);
                        }
                        Animation translate_in= AnimationUtils.loadAnimation(MainActivity.this,R.anim.translate_in);
                        translate_in.setFillAfter(true);
                        translate_in.setDuration(300);
                        translate_in.setDetachWallpaper(true);
                        webView.setAnimation(translate_in);

                        Animation translate_out=AnimationUtils.loadAnimation(MainActivity.this,R.anim.translate_out);
                        translate_out.setAnimationListener(new Animation.AnimationListener() {
                            @Override
                            public void onAnimationStart(Animation animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                if(null!=imageView){
                                    MainActivity.this.root.removeView(imageView);
                                    imageView=null;
                                    SharedPreferencesUtils.save(MainActivity.this,100,"back");
                                }
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {

                            }
                        });
                        translate_out.setFillAfter(true);
                        translate_out.setDuration(300);
                        translate_out.setDetachWallpaper(true);
                        if(null!=imageView){
                            imageView.setAnimation(translate_out);
                        }
                    }else{
                        root.setVisibility(View.GONE);
                        if(null==imageView){
                            imageView=new ImageView(MainActivity.this);
                            view.setDrawingCacheEnabled(true);
                            Bitmap bitmap=view.getDrawingCache();
                            Bitmap b=Bitmap.createBitmap(bitmap);
                            imageView.setImageBitmap(b);
                            MainActivity.this.root.addView(imageView);
                            imageView.setVisibility(View.VISIBLE);
                        }
                    }


                }else if (nine==999){  // 进入执行的代码
                    if (newProgress==100) {
                        pd.dismiss();
                        webView.setVisibility(View.VISIBLE);
                        if(imageView!=null){
                            imageView.setVisibility(View.GONE);
                            webView.setVisibility(View.VISIBLE);
                        }
                        Animation translate_in= AnimationUtils.loadAnimation(MainActivity.this,R.anim.out);
                        translate_in.setFillAfter(true);
                        translate_in.setDuration(300);
                        translate_in.setDetachWallpaper(true);
                        webView.setAnimation(translate_in);

                        Animation translate_out=AnimationUtils.loadAnimation(MainActivity.this,R.anim.in);
                        translate_out.setAnimationListener(new Animation.AnimationListener() {
                            @Override
                            public void onAnimationStart(Animation animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                webView.setVisibility(View.VISIBLE);
                                if(null!=imageView){
                                    MainActivity.this.root.removeView(imageView);
                                    imageView=null;
                                    SharedPreferencesUtils.save(MainActivity.this,100,"goin");
                                }
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {

                            }
                        });
                        translate_out.setFillAfter(true);
                        translate_out.setDuration(300);
                        translate_out.setDetachWallpaper(true);
                        if(null!=imageView){
                            imageView.setAnimation(translate_out);
                        }
                    }else{
                        root.setVisibility(View.GONE);
                        if(null==imageView){
                            imageView=new ImageView(MainActivity.this);
                            view.setDrawingCacheEnabled(true);
                            Bitmap bitmap=view.getDrawingCache();
                            Bitmap b=Bitmap.createBitmap(bitmap);
                            imageView.setImageBitmap(b);
                            MainActivity.this.root.addView(imageView);
                        }
                    }
                }
else {    //  第一次或者其他执行的代码
                    if (newProgress==100){
                        pd.dismiss();
                    }
                }

                super.onProgressChanged(view, newProgress);
            }
        });
        webView.loadUrl(API.MAIN_URL);
        };



    @Override
    public void onBackPressed() {
        SharedPreferencesUtils.save(MainActivity.this,888,"back");
        goback=true;
        if (webView.canGoBack()){
            webView.goBack();
        }else {
            exit();
        }
    }

    @Override
    public void onDestroy() {
        ClearCacheUtils.cleanDatabases(MainActivity.this);
        finish();
        super.onDestroy();
    }

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), R.string.exit_again,
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, API.HANDLER_MAIN);
        } else {
            super.onBackPressed();
            ClearCacheUtils.cleanDatabases(MainActivity.this);   //暂时可以清楚缓存，当涉及到保存用户账户密码时一定要关闭
            finish();
        }
    }


    public class WebHost {
        public Context context;

        public WebHost(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void acllJs(String url){
//            Toast.makeText(context, url+"", Toast.LENGTH_SHORT).show();
            handler.obtainMessage(233,url).sendToTarget();
        }
    }
}
